package com.sdruixinggroup.mondayb2b.ui;

import android.app.Activity;
import android.app.LocalActivityManager;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TabHost;
import android.widget.TextView;

import com.google.gson.reflect.TypeToken;
import com.sdruixinggroup.mondayb2b.API.API;
import com.sdruixinggroup.mondayb2b.R;
import com.sdruixinggroup.mondayb2b.interfaces.ObjectCallBack;
import com.sdruixinggroup.mondayb2b.models.ModelBeen;
import com.sdruixinggroup.mondayb2b.models.ShoppingCartMessage;
import com.sdruixinggroup.mondayb2b.ui.Activities.ShoppingCartActivity;
import com.sdruixinggroup.mondayb2b.utils.UserInfoUtil;
import com.zhy.http.okhttp.OkHttpUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.jpush.android.api.JPushInterface;
import okhttp3.Call;

/**
 * Created by tangjie on 2017/11/9.
 */
public class MainActivity extends BaseActivity implements
        RadioGroup.OnCheckedChangeListener {
    @BindView(R.id.radio_button_money)
    RadioButton radioButtonMoney;
    @BindView(R.id.radio_button_question)
    RadioButton radioButtonQuestion;
    @BindView(R.id.radio_button_classfiy)
    RadioButton radioButtonClassfiy;
    @BindView(R.id.radio_button_shop)
    RadioButton radioButtonShop;
    @BindView(R.id.radio_button_mine)
    RadioButton radioButtonMine;
    @BindView(R.id.tab_radiogroup)
    LinearLayout tabRadiogroup;
    @BindView(R.id.tv_shop_count)
    TextView tvShopCount;
    private TabHost tabHost;


    private Intent moneyIntent;
    private Intent questionIntent;
    private Intent classfiyIntent;
    private Intent shopIntent;
    private Intent mineIntent;
    private LocalActivityManager groupActivity;
    private List<RadioButton>   RadioButtons ;

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(Object resp) {/* Do something */
        if (resp instanceof Integer) {
            Integer integer = (Integer) resp;
            if (integer == 125) {
                tabRadiogroup.setVisibility(View.VISIBLE);
            } else if (integer == 126) {
                tabRadiogroup.setVisibility(View.GONE);
            }
        }else if(resp instanceof ShoppingCartMessage){
            ShoppingCartMessage shoppingCartMessage = (ShoppingCartMessage)resp;
            int count =shoppingCartMessage.count;
            if(count > 0){
                tvShopCount.setText(String.valueOf(count));
                tvShopCount.setVisibility(View.VISIBLE);
                if(count > 99){
                    tvShopCount.setText(String.valueOf(99)+"+");
                }
            }else {
                tvShopCount.setVisibility(View.GONE);
            }
        }

    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);
        // tabHost = getTabHost();
        tabHost = (TabHost) findViewById(R.id.my_tabhost);
        groupActivity =
                new LocalActivityManager(this, true);
        groupActivity.dispatchCreate(savedInstanceState);
        tabHost.setup(groupActivity);
        RadioButtons = new ArrayList<>();
        RadioButtons.add(radioButtonMoney);
        RadioButtons.add(radioButtonQuestion);
        RadioButtons.add(radioButtonClassfiy);
        RadioButtons.add(radioButtonShop);
        RadioButtons.add(radioButtonMine);
        initIntent();
        addSpec();
     /*   ((RadioGroup) findViewById(R.id.tab_radiogroup));
                .setOnCheckedChangeListener(this);*/

        configureTabInfo(R.drawable.tab_icon1, radioButtonMoney);
        configureTabInfo(R.drawable.tab_icon2, radioButtonQuestion);
        configureTabInfo(R.drawable.tab_icon3, radioButtonClassfiy);
        configureTabInfo(R.drawable.tab_icon4, radioButtonShop);
        configureTabInfo(R.drawable.tab_icon5, radioButtonMine);
        String registration_id = JPushInterface.getRegistrationID(this);
        Log.e("HQQ", " registration_id :" + registration_id);
        String url = API.REGISTRATION_ID + registration_id + "&access_token=" + UserInfoUtil.getInfoToken(getApplicationContext());
        TypeToken<ModelBeen> typeToken = new TypeToken<ModelBeen>() {
        };
        OkHttpUtils.post().url(url).build().execute(new ObjectCallBack<ModelBeen>(typeToken) {
            @Override
            public void onError(Call call, Exception e, int id) {

            }

            @Override
            public void onResponse(ModelBeen response, int id) {
            }
        });

        radioButtonMoney.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                tabHost.setCurrentTabByTag("tab_money");
                setSelector(v.getId());
            }
        });
        radioButtonQuestion.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                tabHost.setCurrentTabByTag("tab_question");
                setSelector(v.getId());
            }
        });

        radioButtonClassfiy.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                tabHost.setCurrentTabByTag("tab_classfiy");
                setSelector(v.getId());
            }
        });

        radioButtonShop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                tabHost.setCurrentTabByTag("tab_shop");
                setSelector(v.getId());
            }
        });

        radioButtonMine.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                tabHost.setCurrentTabByTag("tab_mine");
                setSelector(v.getId());
            }
        });
    }

    /**
     * 初始化各个tab标签对应的intent
     */
    private void initIntent() {
        moneyIntent = new Intent(this, HomeActivity.class);
        questionIntent = new Intent(this, WebActivity.class);
        questionIntent.putExtra(WebActivity.INTENT_EXTRA_BEGIN_URL, "questions?");
        questionIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        classfiyIntent = new Intent(this, ClassifyActivity.class);
        shopIntent = new Intent(this, ShoppingCartActivity.class);
        shopIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        mineIntent = new Intent(this, MineActivity.class);
        mineIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

    }

    /**
     * 为tabHost添加各个标签项
     */
    private void addSpec() {
        tabHost.addTab(this.buildTagSpec("tab_money", R.string.app_name,
                R.drawable.tab_icon1, moneyIntent));
        tabHost.addTab(this.buildTagSpec("tab_question", R.string.app_name,
                R.drawable.tab_icon2, questionIntent));
        tabHost.addTab(this.buildTagSpec("tab_classfiy", R.string.app_name,
                R.drawable.tab_icon3, classfiyIntent));
        tabHost.addTab(this.buildTagSpec("tab_shop",
                R.string.app_name, R.drawable.tab_icon4,
                shopIntent));
        tabHost.addTab(this.buildTagSpec("tab_mine", R.string.app_name,
                R.drawable.tab_icon5, mineIntent));
    }

    /**
     * 自定义创建标签项的方法
     *
     * @param tagName  标签标识
     * @param tagLable 标签文字
     * @param icon     标签图标
     * @param content  标签对应的内容
     * @return
     */
    private TabHost.TabSpec buildTagSpec(String tagName, int tagLable,
                                         int icon, Intent content) {
        return tabHost
                .newTabSpec(tagName)
                .setIndicator(getResources().getString(tagLable),
                        getResources().getDrawable(icon)).setContent(content);
    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        Log.e("HQQ","onCheckedChanged: "+checkedId);
        radioButtonShop.setChecked(false);
        setSelector(checkedId);
        switch (checkedId) {
            case R.id.radio_button_money:
                tabHost.setCurrentTabByTag("tab_money");
                break;
            case R.id.radio_button_question:
                tabHost.setCurrentTabByTag("tab_question");
                break;
            case R.id.radio_button_classfiy:
                tabHost.setCurrentTabByTag("tab_classfiy");
                break;
          /*  case R.id.radio_button_shop:
                tabHost.setCurrentTabByTag("tab_shop");
                break;*/
          /*  case R.id.rl_button_shop:
                tabHost.setCurrentTabByTag("tab_shop");
                break;*/
            case R.id.radio_button_mine:
                tabHost.setCurrentTabByTag("tab_mine");
                break;
        }

    }

    private void configureTabInfo(int drawableRes, RadioButton tv) {
        int size = getResources().getDimensionPixelSize(R.dimen.tab_icon_size);
        Drawable recommendDrawable = getResources().getDrawable(drawableRes);
        recommendDrawable.setBounds(0, 0, size, size);
        tv.setCompoundDrawables(null, recommendDrawable, null, null);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (!UserInfoUtil.getIsLogin(getApplicationContext())) {
            tabHost.setCurrentTabByTag("tab_money");
            setSelector(R.id.radio_button_money);
        }

     /*   Activity subActivity = groupActivity.getActivity("tab_money");
        if(null != subActivity){
            ((HomeActivity)subActivity).starBanner();
        }*/
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // 获取当前活动的Activity实例\
        Activity subActivity = groupActivity.getActivity("tab_question");
        Activity mindActivity = groupActivity.getActivity("tab_mine");
        //  Activity subActivity =groupActivity.getCurrentActivity();
        //判断是否实现返回值接口
        if (subActivity instanceof OnTabActivityResultListener  ) {
            //获取返回值接口实例
            OnTabActivityResultListener listener = (OnTabActivityResultListener) subActivity;
            //转发请求到子Activity
            listener.onTabActivityResult(requestCode, resultCode, data);
        }else if( mindActivity instanceof OnTabActivityResultListener){
            OnTabActivityResultListener listener = (OnTabActivityResultListener) mindActivity;
            //转发请求到子Activity
            listener.onTabActivityResult(requestCode, resultCode, data);
        }

        super.onActivityResult(requestCode, resultCode, data);
    }

    public interface OnTabActivityResultListener {
        public void onTabActivityResult(int requestCode, int resultCode, Intent data);
    }


    private void setSelector(int id){
        for(RadioButton radioButton :RadioButtons){
            if(radioButton.getId() == id){
                radioButton.setChecked(true);
            }else {
                radioButton.setChecked(false);
            }
        }
    }


/*    @Override
    protected void onStop() {
        super.onStop();
        Log.e("HQQ","onStop:   dddd  ");
        Activity subActivity = groupActivity.getActivity("tab_money");
        if(null != subActivity){
            ((HomeActivity)subActivity).onStop();
        }
    }*/

}


